package top.eggcode.plugins.session.store;

import top.eggcode.plugins.session.IdGenerator;
import top.eggcode.plugins.session.Session;
import top.eggcode.plugins.session.SimpleIdGenerator;
import top.eggcode.plugins.session.SimpleSession;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Title: 基于内存的session持久化
 * Description: TODO
 * Date: 2021/7/24 23:10
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class MemorySessionStore implements SessionStore {

    private final Map<String, Object> sessions = new ConcurrentHashMap<>();

    private IdGenerator idGenerator = new SimpleIdGenerator();

    @Override
    public Serializable create(Session session) {
        Serializable sessionId = idGenerator.generateId(session);
        // 强制转换
        ((SimpleSession) session).setId(sessionId);
        this.saveSession(session.getId(), session);
        return sessionId;
    }

    @Override
    public Session readSession(Serializable sessionId) {
        return (Session) this.sessions.get(sessionId);
    }

    @Override
    public void update(Session session) {
        this.saveSession(session.getId(), session);
    }

    @Override
    public void delete(Session session) {
        if (session == null) {
            throw new NullPointerException("session argument cannot be null.");
        } else {
            Serializable id = session.getId();
            if (id != null) {
                this.sessions.remove(id);
            }
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }

    protected Session saveSession(Serializable id, Session session) {
        return (Session) sessions.putIfAbsent((String) session.getId(), session);
    }
}
